package cn.senwill.order_service.controller;

import cn.senwill.order_service.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RefreshScope// 当配置中心更新改变时，局部刷新该区域
@RestController
@RequestMapping(value = "api/v1/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping(value = "save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("userId") Integer userId, @RequestParam("productId") Integer productId, HttpServletRequest request) {

        // zuul默认配置不可获取cookie、Set-Cookie、Authorization，因为这3个值比较敏感
        String token = request.getHeader("token");
        System.out.println("token => " + token);
        String cookie = request.getHeader("cookie");
        System.out.println("cookie => " + cookie);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "下单成功");
        map.put("data", orderService.save(userId, productId));
        return map;
    }

    /**
     * saveOrderFail的fallbackMethod方法
     * @param userId
     * @param productId
     * @return
     */
    private Object saveOrderFail(Integer userId, Integer productId, HttpServletRequest request) {
        // 监控报警
        String saveOrderKey = "save-order";
        String saveOrderValue = redisTemplate.opsForValue().get(saveOrderKey);

        // 异步执行，开启一个线程操作Redis和发送短信
        new Thread(
                () -> {
                    if (StringUtils.isBlank(saveOrderValue)) {
                        System.out.println("紧急短信，来自 " + request.getRemoteAddr().toString() + " IP的用户下单失败，请查找原因");
                        // 发送短信代码...
                        redisTemplate.opsForValue().set(saveOrderKey, "save-order-fail", 30, TimeUnit.SECONDS);
                    } else {
                        System.out.println("已经发送过短信，30秒内不重复发送");
                    }
                }
        ).start();

        Map<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("msg", "下单失败，请稍后再试");
        System.out.println(map);
        return map;
    }
}
